package chapter3to7.src.main.java.com.kaikeba.concurrent;

/**
 * @author : wushikai
 * <p>
 * date : 2021-03-22
 */

public class WaitAndNotify {


    final Object object = new Object();

    public class MyThread_1 extends Thread {
        @Override
        public void run() {
            while (true) {
                synchronized (object) {
                    object.notify();
                    System.out.println(System.currentTimeMillis() + "  T1 start");
                    try {
                        System.out.println(System.currentTimeMillis() + "   T1 wait");
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(System.currentTimeMillis() + "   T1 end");
                }
            }

        }
    }

    public class MyThread_2 extends Thread {
        @Override
        public void run() {
            while (true) {
                synchronized (object) {
                    System.out.println(System.currentTimeMillis() + "   T2 start and notify");
                    object.notify();
                    try {
                        System.out.println(System.currentTimeMillis() + "   T2 wait");
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void test() {
        Thread t1 = new MyThread_1();
        Thread t2 = new MyThread_2();
        t1.start();
        t2.start();
    }


    public static void main(String[] args) {

        new WaitAndNotify().test();
    }
}